package com.bingxue.edu.management.listener;

import cn.hutool.core.util.StrUtil;
import com.bingxue.edu.common.config.NotifyConfigProperties;
import com.bingxue.edu.common.config.WechatProperties;
import com.bingxue.edu.common.enums.EmployeeTypeEnum;
import com.bingxue.edu.management.education.model.entity.ClassInfo;
import com.bingxue.edu.management.education.model.entity.Enrollment;
import com.bingxue.edu.management.education.model.entity.Student;
import com.bingxue.edu.management.education.service.ClassInfoService;
import com.bingxue.edu.management.education.service.EnrollmentService;
import com.bingxue.edu.management.education.service.StudentService;
import com.bingxue.edu.management.event.EnrollPassedEvent;
import com.bingxue.edu.management.shop.activity.LdxActivityService;
import com.bingxue.edu.management.shop.model.entity.OrderItem;
import com.bingxue.edu.management.shop.service.OrderItemService;
import com.bingxue.edu.management.shop.service.SellRecordService;
import com.bingxue.edu.management.system.model.entity.Employee;
import com.bingxue.edu.management.system.service.EmployeeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.message.WxCpMessage;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionalEventListener;

import java.util.LinkedHashMap;
import java.util.LinkedList;

import static com.bingxue.edu.common.constant.DateConstants.FORMATTER_TIME_HHmm_CN;

/**
 * @author panbo
 * @since 2024/11/12
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class EnrollPassedEventListener {

    private final NotifyConfigProperties notifyConfigProperties;
    private final WechatProperties wechatProperties;
    private final WxCpService wxCpService;

    private final EnrollmentService enrollmentService;
    private final OrderItemService orderItemService;
    private final EmployeeService employeeService;
    private final SellRecordService sellRecordService;
    private final LdxActivityService ldxActivityService;
    private final ClassInfoService classInfoService;
    private final StudentService studentService;

    @Async
    @TransactionalEventListener(fallbackExecution = true)
    public void onEventListen(EnrollPassedEvent event) {
        Enrollment enrollment = enrollmentService.getById(event.getEnrollmentId());

        String orderItemId = event.getOrderItemId();
        OrderItem orderItem = orderItemService.getById(orderItemId);

        ldxActivityService.process(enrollment, orderItem);
        updateEnrollSeller(enrollment, orderItem);
        sendNotify(enrollment, orderItem);
    }


    /**
     * 设置销售顾问
     */
    private void updateEnrollSeller(Enrollment enrollment, OrderItem orderItem) {
        try {
            String createUser = orderItem.getCreateUser();
            // 必须是后台创建
            if (StrUtil.isEmpty(createUser)) {
                return;
            }
            // 创建者必须是销售顾问
            Employee employee = employeeService.getById(createUser);
            if (employee == null || employee.getType() != EmployeeTypeEnum.SELLER) {
                return;
            }

            // 设置报名信息销售顾问
            Enrollment updateEnrollment = new Enrollment();
            updateEnrollment.setId(enrollment.getId());
            updateEnrollment.setSellerId(employee.getId());
            enrollmentService.updateById(updateEnrollment);
            log.info("设置销售顾问成功, 报名id: {}, 销售顾问: {}", enrollment.getId(), employee.getId());

            // 添加销售业绩记录
            sellRecordService.createEnrollSellRecord(enrollment, orderItem, employee.getId());
        } catch (Exception e) {
            log.error("设置销售顾问失败: {}", e.getMessage(), e);
        }

    }

    private void sendNotify(Enrollment enrollment, OrderItem orderItem) {
        NotifyConfigProperties.SceneConfig classEnrollSuccessConfig = notifyConfigProperties.getEnrollPassedTip();
        if (!classEnrollSuccessConfig.isTeacherWecomEnabled()) {
            return;
        }
        try {
            String classId = enrollment.getClassId();
            Student student = studentService.getById(enrollment.getStudentId());
            ClassInfo classInfo = classInfoService.getById(classId);

            LinkedList<String> userCodeList = new LinkedList<>();
            if (StrUtil.isNotEmpty(classInfo.getLeadTeacherId())) {
                Employee leadTeacher = employeeService.getById(classInfo.getLeadTeacherId());
                userCodeList.push(leadTeacher.getCode());
            }
            if (StrUtil.isNotEmpty(classInfo.getAssistTeacherId())) {
                Employee assistTeacher = employeeService.getById(classInfo.getAssistTeacherId());
                userCodeList.push(assistTeacher.getCode());
            }
            if (userCodeList.isEmpty()) {
                return;
            }
            String toUser = String.join("|", userCodeList);
            WxCpMessage wxCpMessage = new WxCpMessage();
            wxCpMessage.setSafe("0");
            wxCpMessage.setMsgType(WxConsts.KefuMsgType.MINIPROGRAM_NOTICE);
            wxCpMessage.setAppId(wechatProperties.getEmployeeAppId());
            wxCpMessage.setToUser(toUser);
            wxCpMessage.setPage(String.format("pages/class/detail?id=%s", classId));
            wxCpMessage.setTitle("学生报名通知");
            wxCpMessage.setDescription(enrollment.getCreateTime().format(FORMATTER_TIME_HHmm_CN));
            LinkedHashMap<String, String> items = new LinkedHashMap<>();
            items.put("学生", student.getName());
            items.put("联系方式", student.getParentPhone());
            items.put("报名班级", classInfo.getName());
            items.put("报名课次", String.format("%d节", orderItem.getLessonIndexes().size()));
            items.put("班级名额", String.format("%d/%d", classInfo.getEnrollStudentCount(), classInfo.getPlanStudentCount()));
            wxCpMessage.setContentItems(items);
            wxCpMessage.setEmphasisFirstItem(true);
            wxCpService.getMessageService().send(wxCpMessage);
            log.error("发送企业微信通知成功：报名通知");
        } catch (Exception e) {
            log.error("发送企业微信通知失败, {}", e.getMessage(), e);
        }
    }
}
